#include "experimentexportui.h"
#include "ui_experimentexportui.h"

ExperimentExportUi::ExperimentExportUi(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ExperimentExportUi)
{
    ui->setupUi(this);

    /* 实例化 */
    exportNotice = new CustomMessageBox();
    cusMsg = new CustomMessageBox();

    /* 限制文本框输入限制 */
    /* 实验名称 */
    QRegExp expRepNamerx("(\\w|-|\\s){1,50}");
    QRegExpValidator *expRepNameReg = new QRegExpValidator(expRepNamerx, this);
    ui->editName->setValidator(expRepNameReg);

    /* 设置默认选中不可更改 */
    ui->sampleInfo->setEnabled(false);
    ui->procedureData->setEnabled(false);
    ui->yuanShiYingGuang->setEnabled(false);
    ui->resultCurveInfo->setEnabled(false);

    /* 上一步按钮 */
    connect(ui->previousBtn, &QPushButton::clicked, this, [=](){
        emit ExperimentExportUi::previousEvent();
    });

    /* 初始化 */
    /* 导出样本信息 */
    this->checkBoxChanged(ui->sampleInfo, "export-sample-info");
    /* 导出扩增数据 */
    this->checkBoxChanged(ui->procedureData, "export-procedure-data");
    /* 原始荧光 */
    this->checkBoxChanged(ui->yuanShiYingGuang, "export-dissolution-result"); // 这里的第二个参数不要修改为 "yuanShiYingGuang"
    /* 自动导出 */
    this->checkBoxChanged(ui->autoExport, "auto-export");

    /* 导出文件类型变化 */
    connect(ui->editType, &QComboBox::currentTextChanged, this, [=](QString text){
        this->configData = preferencesService->getPreferencesData();
        this->configData["export-file-format"] = text;
        preferencesService->updatePreferences(this->configData);
    });

    /* 选择导出路径 */
    connect(ui->chooseLoc, &QPushButton::clicked, this, [=](){
        this->completeDirPath = QFileDialog::getExistingDirectory(
                    this,
                    "选择导出路径",
                    configData["file-path"]
                );
        LOG << this->completeDirPath;
        ui->editLoc->setText(this->completeDirPath);
    });

    /* 数据导出 */
    connect(ui->exportExpBtn, &QPushButton::clicked, this, &ExperimentExportUi::exportExperimentData);

    /* 数据保存 */
    connect(ui->saveBtn, &QPushButton::clicked, this, [=](){
        emit ExperimentExportUi::saveEvent();
    });

    LOG << "导出结束";

}

ExperimentExportUi::~ExperimentExportUi()
{
    delete ui;
}

/* 获取 导入 所需数据 */
void ExperimentExportUi::getExportData(){
//void ExperimentExportUi::getExportData(Experiment experiment, ReactionPlate reactionPlate, ConnectedDeviceStruct device, QList<QList<QHash<QString, QString>>> saveYingguangDataList, ExportFileService *exportFileService, QHash<QHash<QString,QString>,QList<QHash<QString,QString>>> procedureList, QHash<QString, QString> targetLegend, QList<QString> ct, PreferencesService *preference){

//    this->device = device;
//    this->experiment = experiment;
//    this->targetLegend = targetLegend;

//    this->experimentName = experiment.experiment_name;
//    this->reactionPlate = reactionPlate;
//    this->saveYingguangDataList =  saveYingguangDataList; // 荧光数据列表;
//    this->exportFileService = exportFileService;
//    this->procedureList = procedureList;
//    this->preferencesService = preference;
//    this->ct = ct;

    /* 渲染配置文件 */
    this->renderConfigExport();

    LOG << "导出结束";
}


/* 复选框项目变化 */
void ExperimentExportUi::checkBoxChanged(QCheckBox* obj, QString item){
    connect(obj, &QCheckBox::toggled, this, [=](bool checked){
        if(checked)
            this->configData[item] = "1";
        else
            this->configData[item] = "0";
        preferencesService->updatePreferences(this->configData);
    });
}

/* 导出实验文件 */
void ExperimentExportUi::exportExperimentData(){
    /* 获取输入框内的文件名称 */
    QString exportFileName = ui->editName->displayText();

    /* 合并基本信息 */
    this->exportBasicData.clear(); // 清空合并的基本信息
    this->jointBasicData(); // （重新）合并基本信息

    LOG << "exportBasicData" << exportBasicData;

    /* 提示框显示 */
    exportNotice->normalShow(this, CMsg::CNoButton, CMsg::CInformation, "实验导出", "实验内容导出中，请稍后...");

    /* 如果输入框内的文件名称为空，则换为默认的实验名称为导出文件名称 */
    if(exportFileName == ""){
        exportFileName = this->experiment.experiment_name;
    }

    /* 如果实验id为空 */
    if(this->experiment.experiment_id == ""){
        exportNotice->normalHide();
        cusMsg->show(this, CMsg::CCritical, "错误", "实验ID为空，导出失败");
        return;
    }

    LOG << "导出路径" << this->completeDirPath;

    /* 导出服务初始化 */
    if(exportFileService->init(this->experiment.experiment_id, exportFileName, this->completeDirPath + "/")){

        LOG << "init函数结束";

        /* 发送样本数据 */
        if(!exportFileService->yangben2EXCEL(exportBasicData, reactionPlate.sampleList, reactionPlate.targetList)){
            exportNotice->normalHide();
            cusMsg->show(this, CMsg::CCritical, "错误", "数据导出失败，请关闭打开的文件或检查路径后重新尝试！");
        }
        /* 发送扩增数据 */
        if(!exportFileService->kuozeng2EXCEL(exportBasicData, this->alysYingguangDataList, this->deltaYingguangDataList, this->targetLegend, this->ct, this->reactionPlate.consumables)){
            exportNotice->normalHide();
            cusMsg->show(this, CMsg::CCritical, "错误", "数据导出失败，请关闭打开的文件或检查路径后重新尝试！");
        }
        /* 发送解析后的荧光数据 */
        if(!exportFileService->yingguang2EXCEL(exportBasicData, this->deltaYingguangDataList)){
            exportNotice->normalHide();
            cusMsg->show(this, CMsg::CCritical, "错误", "数据导出失败，请关闭打开的文件或检查路径后重新尝试！");
        }
        /* 发送荧光数据 */
        if(!exportFileService->yuanshi2EXCEL(exportBasicData, this->saveYingguangDataList)){
            exportNotice->normalHide();
            cusMsg->show(this, CMsg::CCritical, "错误", "数据导出失败，请关闭打开的文件或检查路径后重新尝试！");
        }
        /* 调用导出结束函数 */
        if(!exportFileService->exportFinished()){
            exportNotice->normalHide();
            cusMsg->show(this, CMsg::CCritical, "错误", "数据导出失败，请关闭打开的文件或检查路径后重新尝试！");
        }
        /* 导出成功 */
        exportNotice->normalHide();
        cusMsg->show(this, CMsg::CInformation, "导出", "实验数据导出成功！");
    }
    else {
        exportNotice->normalHide();
        cusMsg->show(this, CMsg::CCritical, "错误", "数据导出失败，请关闭打开的文件或检查路径后重新尝试！");
    }
}

/* 渲染配置文件 */
void ExperimentExportUi::renderConfigExport(){
    /* 文件名 */
    ui->editName->setText(this->experimentName);
    /* 其他属性 */
    this->configData.clear();
    this->configData = preferencesService->getPreferencesData();

    /* 实验完成后是否自动导出 */
    if(configData["auto-export"] == "1")
        ui->autoExport->setCheckState(Qt::Checked);
    else {
        ui->autoExport->setCheckState(Qt::Unchecked);
    }
    /* 默认导出报告格式 */
    ui->editType->setCurrentText(configData["export-file-format"]);
    /* 样本信息 */
    if(configData["export-sample-info"] == "1")
        ui->sampleInfo->setCheckState(Qt::Checked);
    else
        ui->sampleInfo->setCheckState(Qt::Unchecked);
    /* 扩增信息 */
    if(configData["export-procedure-data"] == "1")
        ui->procedureData->setCheckState(Qt::Checked);
    else
        ui->procedureData->setCheckState(Qt::Unchecked);
    /* 溶解曲线结果 */
    if(configData["export-dissolution-result"] == "1")
        ui->yuanShiYingGuang->setCheckState(Qt::Checked);
    else
        ui->yuanShiYingGuang->setCheckState(Qt::Unchecked);
    /* 导出路径 */
    ui->editLoc->setText(this->configData["file-path"]);
    /* 设置默认路径 */
    this->completeDirPath = configData["file-path"];

}

/* 拼合导出基本数据 */
void ExperimentExportUi::jointBasicData(){
    /* 获取当前日期时间 */
    QDateTime expTime = QDateTime::currentDateTime();
    /* 转QString */
    QString expStringDate = expTime.toString("yyyy-MM-dd hhmmss");

    exportBasicData.append(device.dev.name); // 设备名称
    exportBasicData.append(device.dev.id); // 设备型号
    exportBasicData.append(device.dev.serial_number); // 设备序列号
    exportBasicData.append(""); // 信号平滑
    exportBasicData.append(expStringDate); // 创建日期
    exportBasicData.append(canBi); // 参比荧光
    exportBasicData.append(experiment.experiment_name); // 实验名称
    exportBasicData.append(wlkFileName); // 实验文件名
    exportBasicData.append(experiment.coding); // 实验编码
    exportBasicData.append(experiment.experiment_remarks); // 实验注释
    exportBasicData.append(experiment.plate_remarks); // 反应版注释
    exportBasicData.append(experiment.type); // 实验类型
    exportBasicData.append(endTime); // 运行结束时间
    exportBasicData.append(experiment.user_name); // 用户名
    exportBasicData.append(""); // 读后阶段/步骤数
    exportBasicData.append(""); // 量化循环数方法
    exportBasicData.append(""); // 预读阶段/步骤数

}

/* 所有组件失效 */
void ExperimentExportUi::allComponentsInvalid(){
    ui->exportExpBtn->setEnabled(false);
}

/* 所有组件生效 */
void ExperimentExportUi::allComponentsValid(){
    ui->exportExpBtn->setEnabled(true);
}

/* 休眠函数 */
void ExperimentExportUi::sleep(int msec){
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime)
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

/* 鼠标聚焦实验名称文字框 2023.6.2*/
void ExperimentExportUi::setFocusToFileNameLineEdit()
{
    if(ui->editName->isVisible()){
        ui->editName->setFocus(); // 设置组件聚焦
    }

}

/* 窗口显示函数 */
void ExperimentExportUi::showEvent(QShowEvent *event){

}
